<template>
  <div class='actionBarBody' style="float: left; padding-bottom: 10px;margin-top: 10px;">
    <el-tooltip class="item" effect="dark" content="权限控制" placement="top">
      <button class="privilege-button" id="privilegeButton">
        <i class="fas fa-lock"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="导入文件" placement="top">
      <button class="importButton">
        <i class="fas fa-cloud-download-alt"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="导出文件" placement="top">
      <button class="outPortButton">
        <i class="fas fa-cloud-upload-alt"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="格式化代码" placement="top">
      <button class="codeFormat" @click="formatSql(mode.toLowerCase())">
        <i class="fas fa-code"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="代码模板" placement="top">
      <button class="codeTemplate">
        <el-dropdown trigger="click" @command="handleCommand" class="templateContainer">
      <span class="el-dropdown-link">
         <i class="fas fa-file-code"></i>
      </span>
          <el-dropdown-menu slot="dropdown" class="template-dropdown-menu">
            <div class="dropdown-filter">
              <el-input
                  placeholder="过滤模板..."
                  v-model="filterText"
                  size="small"
                  class="filterInput">
              </el-input>
            </div>
            <div class="template-dropdown-content">
              <el-dropdown-item
                  v-for="(item, index) in filteredItems"
                  :key="index"
                  :command="item"
                  :disabled="item.disabled"
                  :divided="item.divided"
              >
                <div class="template-item"
                     @mouseover="showTooltip($event, item.value)"
                     @mouseleave="hideTooltip">
                  <span class="template-item-text">{{ truncateText(item.name) }}</span>
                  <span class="template-item-type">{{ truncateText(item.type) }}</span>
                </div>
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </el-dropdown>
        <div v-if="tooltipVisible" class="tooltip" :style="tooltipStyle">{{ tooltipContent }}</div>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="任务状态" placement="top">
      <button class="jobStatus">
        <span>READY</span>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="运行" placement="top">
      <button class="jobRun" @click="runCode">
        <i class="fas fa-play"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="代码折叠" placement="top">
      <button class="codeFold" @click="changeFold">
        <i class="fa fa-compress-arrows-alt"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="隐藏代码" placement="top">
      <button class="codeHide" @click="changeHide">
        <i class="fas fa-eye"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="隐藏结果" placement="top">
      <button class="resultFold">
        <i class="fas fa-book-open"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="编辑器设置" placement="top">
      <button class="setting">
        <i class="fas fa-cog"></i>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="设置Code类型" placement="top">
      <button>
        <el-select
            class="custom-select"
            v-model="mode"
            placeholder="请选择代码类型"
            size="mini"
            @change="changeMode()"
        >
          <el-option
              v-for="item in modes"
              :key="item"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="点击复制代码" placement="top">
      <button class="copy-button" id="copyButton" @click="copy">
      <span v-if="!isCopied">
        <i class="fas fa-copy"></i>
        <span class="copy-text">复制代码</span>
      </span>
        <span v-else>
        <i class="fas fa-check"></i>
        <span class="copied-text">已复制</span>
      </span>
      </button>
    </el-tooltip>
  </div>
</template>

<script>
import {format} from 'sql-formatter';
export default {
  name: "ActionBar",
  props: {
    editorValue: '',
    setValue: Function,
    isCopied: false,
    changeHideStatus: Function,
    changeFoldStatus: Function,
    copyValue: Function,
    setDialect: Function,
    runCode: Function,
  },
  data() {
    return {
      editorHeight: 30, // 初始高度，稍后会根据内容调整
      code: '',
      formattedSql: '',
      mode: 'mysql',
      modes: ['mysql', 'sql', 'hive', 'sparkSql', 'redshift', 'flinkSql', 'Doris', 'DB2'],
      filterText: '',
      tooltipVisible: false,
      tooltipStyle: {top: '0px', left: '0px'},
      tooltipContent: '',
      menuItems: [
        {name: '基本查询11111111111111111111111111111111', type: '查询', value: "select * from user where name=''"},
        {name: '时间日期', type: '函数', value: "select dateformat(now(),'YYYY-MM-DD HH:mm:ss')"},
        {name: '函数开窗', type: '函数', divided: true, value: "sum over (partition by a order by)"},
        {name: '建表语句', type: '自定义', disabled: true, value: "create table user(id int,name varchar(20))"},
        {
          name: '更新语句', type: '自定义', divided: true, value: "SELECT\n" +
              "  name,\n" +
              "  age,\n" +
              "  sex,\n" +
              "  sum(price) / sum(value) AS single,\n" +
              "  CASE\n" +
              "    WHEN user_info.user_type IS NULL\n" +
              "    OR user_info.user_type = '' THEN CASE\n" +
              "      WHEN nu.buyer_id IS NOT NULL THEN 'new'\n" +
              "      ELSE 'dormant'\n" +
              "    END\n" +
              "    ELSE user_info.user_type\n" +
              "  END AS user_type\n" +
              "FROM\n" +
              "  (\n" +
              "    SELECT\n" +
              "      *\n" +
              "    FROM\n" +
              "      (\n" +
              "        SELECT\n" +
              "          *\n" +
              "        FROM\n" +
              "          user\n" +
              "      ) a\n" +
              "    WHERE\n" +
              "      a = 1\n" +
              "  )\n" +
              "WHERE\n" +
              "  aaa = 1\n" +
              "  AND sex > 2\n" +
              "update user set name='张三' where id=1"
        },
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
        {name: '更新语句', type: '自定义', divided: true, value: "update user set name='张三' where id=1"},
      ]
    };
  },
  computed: {
    filteredItems() {
      if (!this.filterText) {
        return this.menuItems;
      }
      const filterText = this.filterText
      // 模糊查询进行过滤
      return this.menuItems.filter(item => {
        return item.name.toLowerCase().includes(filterText.toLowerCase()) ||
            item.type.toLowerCase().includes(filterText.toLowerCase());
      });
    }
  },
  methods: {
    changeMode() {
      this.setDialect(this.mode);
    },
    showTooltip(event, value) {
      const target = event.currentTarget;
      const rect = target.getBoundingClientRect();

      // Set tooltip content and visibility
      this.tooltipContent = value;
      this.tooltipVisible = true;

      // Calculate tooltip position
      this.tooltipStyle = {
        top: `${rect.top + window.scrollY}px`,
        left: `${rect.right + window.scrollX + 40}px`, // Offset from the right edge of the item
        position: 'absolute',
        zIndex: 1000
      };
      console.log(this.tooltipStyle.top, this.tooltipStyle.left)
    },
    hideTooltip() {
      this.tooltipVisible = false;
      this.tooltipContent = '';
    },
    getEditorValue() {
      console.log(this.editorValue)
    },
    formatSql(sqlType = 'mysql') {
      this.formattedSql = format(this.editorValue, {
        language: sqlType,  // 设置 SQL 语言方言
        indent: '    ',    // 设置缩进为4个空格
        linesBetweenQueries: 2,
        keywordCase: 'upper'
      });
      this.setValue(this.formattedSql);
    },
    copy() {
      this.copyValue();
    },
    changeHide() {
      this.changeHideStatus();
    },
    changeFold() {
      this.changeFoldStatus();
    },
    handleCommand(command) {
      console.log('Selected item:', command);
      // 你可以在这里添加处理逻辑
      this.setValue(this.editorValue + "\n" + command.value);
    },
    truncateText(text) {
      if (text.length > 4) {
        return text.substring(0, 4) + '...';
      }
      return text;
    }
  },
  mounted() {
  }
}
</script>

<style scoped>
.actionBarBody {
  display: flex;
  justify-content: space-between;
  align-content: space-between;
  align-items: center;
}

.actionBarBody button, .actionBarBody button span {
  margin-left: 5px;
  border: none;
  background: none;
  color: #ccc;
  cursor: pointer;
  font-size: 16px;
}

.actionBarBody button:hover {
  color: white;
}

.actionBarBody button .custom-select {
  width: 125px;
}

/*.copy-button {*/
/*  border: none;*/
/*  color: #ccc;*/
/*  cursor: pointer;*/
/*  font-size: 14px;*/
/*}*/
.copy-button:hover {
  color: white;
}

.copy-button .fa-copy {
  margin-right: 4px;
}

.copied-text {
  margin-left: 5px;
  color: white;
  font-weight: bold;
}

.template-dropdown-menu {
  width: 240px; /* Adjust the width as needed */
  max-height: 280px; /* Set the max height as needed */
  overflow-y: auto; /* Add vertical scrollbar if content exceeds max height */
  overflow-x: hidden; /* Hide horizontal overflow */
}

.template-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
}

.template-item-type {
  font-size: 12px;
  color: #888; /* Adjust the color as needed */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dropdown-filter {
  display: flex;
  justify-content: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.dropdown-filter el-input {
  width: 90%; /* Set the width to 60% of the menu */
}

.templateContainer {
  position: relative; /* Ensure tooltip is positioned relative to this container */
}

.tooltip {
  position: absolute;
  background-color: #7f97f7;
  color: #fff;
  padding: 5px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 1001;
  white-space: normal; /* 允许换行 */
  word-wrap: break-word; /* 允许长单词换行 */
  max-width: 240px; /* 设置最大宽度，超过则换行 */
}

/*.template-dropdown-content {*/
/*  max-height: calc(100% - 50px); !* Adjust according to the filter input height *!*/
/*  overflow-y: auto;*/
/*}*/
</style>
